import Vue from "vue";
import VueRouter, { RouteConfig } from "vue-router";
import { Cache } from "@/common/cache";
import store from "@/store";

Vue.use(VueRouter);

const Base = () => import("@/views/Base.vue");
const Home = () => import("@/views/Home.vue");
const MyQuestion = () => import("@/views/MyQuestion.vue");
const Question = () => import("@/views/Question.vue");
const MyAnswer = () => import("@/views/MyAnswer.vue");
const Answer = () => import("@/views/Answer.vue");
const Detail = () => import("@/views/Detail.vue");


export const HOME_ROUTE: RouteConfig = {
  path: "/home",
  name: "home",
  component: Home
};

export const MY_QUESTION_ROUTE: RouteConfig = {
  path: "/my_question",
  name: "my_question",
  component: MyQuestion
}

export const QUESTION_ROUTE: RouteConfig = {
  path: "/question",
  name: "question",
  component: Question
}

export const MY_ANSWER_ROUTE: RouteConfig = {
  path: "/my_answer",
  name: "my_answer",
  component: MyAnswer
}

export const ANSWER_ROUTE: RouteConfig = {
  path: "/answer",
  name: "answer",
  component: Answer
}

export const DETAIL_ROUTE: RouteConfig = {
  path: "/detail",
  name: "detail",
  component: Detail
}

const routes: Array<RouteConfig> = [
  {
    path: "*",
    name: "base",
    component: Base,
    redirect: HOME_ROUTE,
    children: [
      HOME_ROUTE,
      MY_QUESTION_ROUTE,
      QUESTION_ROUTE,
      MY_ANSWER_ROUTE,
      ANSWER_ROUTE,
      DETAIL_ROUTE
    ]
  }
];

const router = new VueRouter({
  mode: "history",
  routes
});

router.beforeEach((to, from, next) => {
  const cachedUserId: string | undefined = Cache.getUserId();
  if (cachedUserId && cachedUserId !== store.getters.userId) {
    store.commit("setUserId", cachedUserId);
  }

  const cachedUserName: string | undefined = Cache.getUserName();
  if (cachedUserName && cachedUserName !== store.getters.name) {
    store.commit("setName", cachedUserName);
  }

  const cachedClientTag: number | undefined = Cache.getClientTag();
  if (cachedClientTag && cachedClientTag !== store.getters.clientTag) {
    store.commit("setClientTag", cachedClientTag)
  }

  next();

});

export default router;
